package com.example.file_management.service;

import com.example.file_management.mapper.user.RoleMapper;
import com.example.file_management.pojo.user.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class RoleService {
    @Autowired
    private RoleMapper roleMapper;

    // 获取所有角色
    public List<Role> getAllRoles() {
        return roleMapper.findAllRoles();
    }

    // 根据ID获取角色
    public Role getRoleById(Long roleId) {
        return roleMapper.findRoleById(roleId);
    }

    public Long getLastInsertId() {
        return roleMapper.getLastInsertId();
    }

    // 检查角色是否存在
    public boolean isRoleNameExists(String roleName) {
        Role.RoleType roleType = Role.RoleType.fromString(roleName);
        if (roleType == null) {
            return false; // 如果找不到匹配的枚举值，则返回false
        }
        return roleMapper.isRoleNameExists(String.valueOf(roleType));
    }

    public boolean isRoleNameExists(Role.RoleType roleName) {
        return roleMapper.isRoleNameExists(String.valueOf(roleName));
    }

    // 创建角色
    public Long createRole(Role role) {
        // 确保角色名在 RoleType 枚举中
        String roleName = role.getRoleName().toString(); // 确保此处为String类型
        Role.RoleType roleType = Role.RoleType.fromString(roleName);
        if (roleType == null) {
            throw new IllegalArgumentException("无效的角色名称: " + roleName);
        }

        // 创建新角色
        role.setRoleName(roleType);
        role.setCreatedAt(LocalDateTime.now());
        roleMapper.insertRole(role);

        // 返回最新插入的 role_id
        return roleMapper.getLastInsertId();
    }

    // 更新角色
    public String updateRole(Role role) {
        if (roleMapper.updateRole(role) > 0) {
            return "角色更新成功";
        }
        return "角色更新失败";
    }

    // 删除角色
    public String deleteRole(Long roleId) {
        if (roleMapper.deleteRole(roleId) > 0) {
            return "角色删除成功";
        }
        return "角色删除失败";
    }

    public boolean hasPermission(String username) {
        // 获取用户的role_id
        Integer roleId = roleMapper.getRoleIdByUsername(username);

        // 检查roleId是否为2（假设2代表"负责人"角色）
        return roleId != null && roleId == 2;
    }
}
